﻿using System;
using System.Collections.Generic;
using CI.Interfaces;
using CI.Mesopotamia.Dal;
using CI.Utils;
using System.Linq;

namespace CI.DAL
{
    /// <summary>
    /// Dal factory
    /// </summary>
    public class DalFactory
    {
        private static readonly SimEnv SimEnv = SimEnv.Instance;

        /// <summary>
        /// get a dal we can use to load
        /// </summary>
        /// <returns></returns>
        public static IDAL GetDalLoad(string environment, IHostingEnvironment hostEnvironment)
        {
            SimEnv.TraceLogger.LogDebug("DalFactory GetDalLoad - Start");

            // preferred ordered list
            // Grid WS
            // XML
            // Test Dal

            // check grid
            var gridWsdal = new GridWSDAL();
            if (GridWSDAL.GridOnline())
            {
                return gridWsdal;
            }

            // check xml db
            var xmlDAL = new XMLDAL();
            if (xmlDAL.LoadHostingEnvironment(environment, hostEnvironment, 0, new List<Guid>()) != null)
            {
                return xmlDAL;
            }

            // else use test db
            var testDAL = new TestDAL();
            return testDAL;
        }

        /// <summary>
        /// get a dal we can use to save with
        /// </summary>
        /// <returns></returns>
        public static IDAL GetDalSave()
        {
            SimEnv.TraceLogger.LogDebug("DalFactory GetDalSave - Start");
            // preferred ordered list
            // Grid WS
            // XML

            // check grid
            var gridWsdal = new GridWSDAL();
            if (GridWSDAL.GridOnline())
            {
                return gridWsdal;
            }

            // else use check xml 
            var xmlDAL = new XMLDAL();
            return xmlDAL;
        }

        public static IEnumerable<Organism.Organism> CreateFittestList(IHostingEnvironment hostEnvironment)
        {
            return hostEnvironment.FitnessFunction.Fittest(hostEnvironment.Organisms).
                            Where(organism => organism.FitnessValue > 0).
                            Cast<Organism.Organism>();
        }


    }
}
